<template>
  <c-dialog ref="dialog" :open-fun="openFun" width="70vw" title="发起异常" @open="openHandle" @close="closeHandle">
    <c-list ref="form" :model="formData" :rules="formRules" :column="2" label-width="150px">
      <c-list-item label="装修任务号" :value="detail.decorationTaskCode" />
      <c-list-item label="门店建设项目号" :value="detail.constCode" />
      <c-list-item label="所属门店" :value="detail.shopName" :span="2" />
      <c-list-item prop="exceptionHandleId" label="异常类型">
        <el-select v-model="formData.exceptionHandleId" placeholder="异常类型" clearable @change="exChangeHandle">
          <el-option v-for="(e,i) in exceptionList" :key="i" :label="e.exceptionType" :value="e.id" />
        </el-select>
      </c-list-item>
      <c-list-item prop="isBpmReview" label="是否需要BPM审批">
        <c-dict-select v-model="formData.isBpmReview" dict-type-code="BOOLEANS" disabled />
      </c-list-item>
      <c-list-item v-if="typeCode==='EXCEPT013'" prop="expectRestoreTime" label="预计恢复时间">
        <el-date-picker
          v-model="formData.expectRestoreTime"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
        />
      </c-list-item>
      <c-list-item v-if="typeCode==='EXCEPT136'" key="EXCEPT136-afterAdjustTime" prop="afterAdjustTime" label="变更后预计进场时间">
        <el-date-picker
          v-model="formData.afterAdjustTime"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
        />
      </c-list-item>
      <c-list-item v-if="typeCode==='EXCEPT019'" prop="delayDay" label="延期天数">
        <c-input-number v-model="formData.delayDay" placeholder="延期天数" clearable @change="delayDayHandle" />
      </c-list-item>
      <c-list-item v-if="(typeCode==='EXCEPT019' && !!formData.delayDay)||typeCode==='EXCEPT136'" prop="expectEndTime" label="变更后预计完工时间">
        <el-date-picker
          v-model="formData.expectEndTime"
          :disabled="typeCode==='EXCEPT019'"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
        />
      </c-list-item>
      <c-list-item v-if="typeCode==='EXCEPT017'" prop="isSampleChange" label="是否涉及定制样品调整">
        <c-dict-select v-model="formData.isSampleChange" placeholder="是否涉及定制样品调整" dict-type-code="BOOLEANS" clearable />
      </c-list-item>
      <c-list-item v-if="formData.isBpmReview===0||formData.isBpmReview==='0'" prop="handler" label="异常处理人">
        <c-single-dialog
          ref="handler"
          v-model="formData.handler"
          :label.sync="handlerName"
          :props="{label:'userName',value:'account'}"
          :focus-query="true"
          :multiple="false"
          :config="{
            title:'异常处理人',
            width:'600px',
            interfacePath:'/slm-admin/api/v1/user/domainUser/page',
            method:'post',
            filtersRaw:[],
            paramsRaw:{},
            setting:[
              {prop:'account',title:'编码',width:80},
              {prop:'userName',title:'名称',width:200},
              {prop:'orgName',title:'组织',width:200}
            ]
          }"
        />
      </c-list-item>
      <c-list-item prop="exceptionDesc" label="异常说明" :span="2">
        <el-input v-model="formData.exceptionDesc" type="textarea" maxlength="1024" show-word-limit :autosize="{minRows: 3}" placeholder="异常说明" clearable />
      </c-list-item>
    </c-list>
    <c-section title="装修过程异常附件">
      <c-file-list v-model="files" view-type="image" type-code="ACCESS019" />
    </c-section>
    <c-section v-if="showDetail" title="异常明细">
      <c-table-box hide-func checkbox :table-config="tableConfig" :table-row-key="tableRowKey" :data="tableData" @selection-change="selectionChange">
        <div slot="btn">
          <c-button type="primary" @click="addTableRow">新增</c-button>
          <c-button type="primary" @click="removeTableRow">删除</c-button>
        </div>
      </c-table-box>
    </c-section>
    <div class="btn-container">
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="confirmHandle">提交</c-button>
    </div>
  </c-dialog>
</template>
<script>
import { postShopException, postExceptionType } from '@/api/decorate'
import { otherFiltersItem, parseTime } from '@/utils'
export default {
  name: 'Abnormal',
  components: {
  },
  props: {
    selData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const validatorHandler = (r, v, c) => {
      if (this.formData.isBpmReview === '0' && !v) {
        c(new Error('请选择处理人'))
      } else {
        c()
      }
    }
    return {
      exceptionList: [],
      typeCode: '',
      files: [],
      handlerName: '',
      formData: {
        exceptionHandleId: '',
        isBpmReview: '',
        expectRestoreTime: '',
        afterAdjustTime: '',
        delayDay: '',
        expectEndTime: '',
        isSampleChange: '',
        handler: '',
        exceptionDesc: ''
      },
      formRules: {
        exceptionHandleId: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
        isBpmReview: [],
        expectRestoreTime: [{ required: true, message: '请选择预计恢复时间', trigger: 'change' }],
        afterAdjustTime: [{ required: true, message: '请选择变更后预计进场时间', trigger: 'change' }],
        delayDay: [{ required: true, message: '请输入延期天数', trigger: 'change' }],
        expectEndTime: [{ required: true, message: '请选择变更后预计完工时间', trigger: 'change' }],
        isSampleChange: [{ required: true, message: '请选择是否涉及定制样品调整', trigger: 'change' }],
        handler: [{ required: false, validator: validatorHandler, trigger: 'change' }],
        exceptionDesc: [{ required: true, message: '请填写异常说明', trigger: 'change' }]
      },
      tableData: [],
      selections: []
    }
  },
  computed: {
    detail() {
      return this.selData.length === 1 ? this.selData[0] : {}
    },
    tableConfig() {
      return {
        interfacePath: '',
        setting: [
          {
            prop: 'exceptionDesc',
            label: '异常描述',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'belongDuty',
            label: '责任归属',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  dictTypeCode: 'BELONG_DUTY',
                  value: row.belongDuty
                },
                on: {
                  input: v => {
                    this.$set(row, 'belongDuty', v)
                  }
                }
              })
              // return h('c-single-dialog', {
              //   props: {
              //     value: row.belongDuty,
              //     label: row.belongDuty,
              //     props: { label: 'belongDuty', value: 'belongDuty' }
              //   },
              //   attrs: {
              //     focusQuery: true,
              //     config: {
              //       title: '责任归属',
              //       width: '600px',
              //       interfacePath: '/slm-admin/api/v1/configAcceptDuty/page',
              //       method: 'post',
              //       // paramField: 'belongDuty',
              //       filtersRaw: [
              //         otherFiltersItem('enable', '1', '=')
              //       ],
              //       paramsRaw: {},
              //       setting: [
              //         { prop: 'belongDuty', title: '编码', width: 80 },
              //         { prop: 'belongDuty', title: '名称', width: 200 }
              //       ]
              //     }
              //   },
              //   on: {
              //     input: v => {
              //       this.$set(row, 'belongDuty', v)
              //     },
              //     'update:label': v => {
              //       this.$set(row, 'belongDutyName', v)
              //     }
              //   }
              // })
            }
          },
          {
            prop: 'picTaskCode',
            label: '选择图纸',
            hidden: this.typeCode !== 'EXCEPT016',
            render: (h, row) => {
              return h('c-single-dialog', {
                props: {
                  value: row.picTaskCode,
                  label: row.picTaskName,
                  props: { label: 'picTaskName', value: 'picTaskCode' }
                },
                attrs: {
                  focusQuery: true,
                  config: {
                    title: '选择图纸',
                    width: '600px',
                    interfacePath: '/slm-admin/api/v1/shopDesignPicture/getDecorationByConstCode',
                    method: 'post',
                    // paramField: 'picTaskName',
                    filtersRaw: [
                      otherFiltersItem('isOutpicUndecoration', '0', '='),
                      otherFiltersItem('constCode', this.detail.constCode, '='),
                      otherFiltersItem('decorationTaskCode', this.detail.decorationTaskCode, '=')
                    ],
                    paramsRaw: {},
                    setting: [
                      { prop: 'picTaskCode', title: '编码', width: 80 },
                      { prop: 'picTaskName', title: '名称', width: 200 }
                    ]
                  }
                },
                on: {
                  input: v => {
                    this.$set(row, 'picTaskCode', v)
                  },
                  'update:label': v => {
                    this.$set(row, 'picTaskName', v)
                  }
                }
              })
            }
          },
          {
            prop: 'cutRegionArea',
            label: '减少装修区域面积',
            render: (h, row) => {
              return h('c-input-number', {
                props: {
                  placeholder: '减少装修区域面积',
                  clearable: true,
                  value: row.cutRegionArea,
                  float: true
                },
                on: {
                  input: v => {
                    this.$set(row, 'cutRegionArea', v)
                  }
                }
              })
            }
          },
          {
            prop: 'remark',
            label: '备注',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          }
        ]
      }
    },
    showDetail() {
      return ['EXCEPT016', 'EXCEPT017'].includes(this.typeCode)
    }
  },
  methods: {
    openFun() {
      if (!this.singleJudge(this.selData, '发起异常', true)) {
        return false
      }
      // 1.当且仅当装修进度值为“装修进场 D、隐蔽工程验收 E、产品复尺 F、初检 G”时，可操作“发起异常”按钮：
      if (!['D', 'E', 'F', 'G', 'H', 'I'].includes(this.detail.schedule)) {
        this.$message.warning('当且仅当装修进度为：装修进场、隐蔽工程验收、产品复尺、初检、装修完工时、验收申请待提报，才可发起异常操作！')
        return false
      }
      return true
    },
    openHandle() {
      const data = new FormData()
      data.append('pageFlag', false)

      const filtersRaw = []
      // const schedule = this.detail.schedule
      const nature = this.detail.nature
      const steps = this.detail.steps

      // 1.1公装：装修进度值为“D-装修进场”，装修步骤为”D1-待进场“时，
      // 可发起的异常类型为“装修终止、变更施工单位、延期进场”，否则系统提示：当前步骤，不能发起此类异常；
      // 1.2公装：装修步骤值为“D2-项目启动会待召开至G2-初检结果审核”时，
      // D2-项目启动会待召开
      // D3-启动会资料待审核
      // E1-隐蔽工程验收
      // E2-隐蔽工程资料审核
      // F1-产品复尺
      // F2-产品复尺资料审核
      // G1-初检
      // G2-初检结果审核
      // 可发起“延期进场”以外的其他异常类型；
      // 2.1自装：装修进度值为“D-装修进场”，装修步骤为”D1-待进场“时，
      // 可发起的异常类型为“装修终止、延期进场”，否则系统提示：当前步骤，不能发起此类异常；
      // 2.2自装：装修步骤值为“D2-项目启动会待召开至G2-初检结果审核”时，
      // 可发起“延期进场、变更施工单位”以外的其他异常类型；

      //  "EXCEPT136 延期进场"
      //  "EXCEPT013 暂停施工"
      //  "EXCEPT014 恢复装修"
      //  "EXCEPT015 终止装修"
      //  "EXCEPT016 减少装修区域"
      //  "EXCEPT017 变更装修内容"
      //  "EXCEPT018 变更施工单位"
      //  "EXCEPT019 施工周期延期"
      if (nature === 'PUBLICS') {
        if (steps === 'D1') {
          filtersRaw.push('EXCEPT015', 'EXCEPT018', 'EXCEPT136')
        } else if ('D2 D3 E1 E2 F1 F2 G1 G2 H1 I1'.includes(steps)) {
          filtersRaw.push('EXCEPT013', 'EXCEPT014', 'EXCEPT015', 'EXCEPT016', 'EXCEPT017', 'EXCEPT018', 'EXCEPT019')
        }
      } else if (nature === 'PRIVATES') {
        if (steps === 'D1') {
          filtersRaw.push('EXCEPT015', 'EXCEPT136')
        } else if ('D2 D3 E1 E2 F1 F2 G1 G2 H1 I1'.includes(steps)) {
          filtersRaw.push('EXCEPT013', 'EXCEPT014', 'EXCEPT015', 'EXCEPT016', 'EXCEPT017', 'EXCEPT019')
        }
      }
      // === ---------------
      // filtersRaw.push('EXCEPT015', 'EXCEPT018', 'EXCEPT136')
      // filtersRaw.push('EXCEPT013', 'EXCEPT014', 'EXCEPT015', 'EXCEPT016', 'EXCEPT017', 'EXCEPT018', 'EXCEPT019')
      // filtersRaw.push('EXCEPT015', 'EXCEPT136')
      // filtersRaw.push('EXCEPT013', 'EXCEPT014', 'EXCEPT015', 'EXCEPT016', 'EXCEPT017', 'EXCEPT019')
      // ===
      data.append('filtersRaw', JSON.stringify([otherFiltersItem('typeCode', `[${filtersRaw.join(',')}]`, 'in')]))
      postExceptionType(data).then(res => {
        this.exceptionList = res.data.records
      })
    },
    exChangeHandle(v) {
      for (const item of this.exceptionList) {
        if (item.id === v) {
          this.$set(this.formData, 'isBpmReview', item.isBpmReview.toString())
          this.typeCode = item.typeCode
          return
        }
      }
      this.$set(this.formData, 'isBpmReview', '')
      this.typeCode = ''
    },
    handlerChange(v) {
      v.length === 0 ? v = {} : v = v[0]
      this.formData.handler = v.agencyCode
    },
    delayDayHandle(v) {
      if (!this.detail.expectEndTime) return
      const t = new Date(this.detail.expectEndTime)
      const d = new Date(t.getFullYear(), t.getMonth(), t.getDate()).getTime()
      this.$set(this.formData, 'expectEndTime', parseTime(d + 1 * v * 24 * 60 * 60 * 1000))
    },
    selectionChange(v) {
      this.selections = v
    },
    tableRowKey(row) {
      return row._key
    },
    addTableRow() {
      this.tableData.unshift({
        exceptionDesc: '',
        belongDuty: '',
        picTaskCode: '',
        picTaskName: '',
        cutRegionArea: '',
        remark: '',
        _key: Math.floor(Math.random() * 0xfffff).toString(16)
      })
    },
    removeTableRow() {
      if (!this.singleJudge(this.selections, '删除', true)) {
        this.$message.warning('请选择数据！')
        return
      }
      this.$msgbox({
        type: 'warning',
        title: '删除',
        message: '确认删除？'
      }).then(() => {
        this.tableData = this.tableData.filter(e => {
          return !this.selections.includes(e)
        })
        this.selections = []
      })
    },
    confirmHandle() {
      return this.$refs.form.validate().then(() => {
        if (['EXCEPT016', 'EXCEPT017'].includes(this.typeCode)) {
          if (this.tableData.length === 0) {
            this.$message.warning('请填写异常明细！')
            return Promise.reject('')
          }
          for (let i = 0; i < this.tableData.length; i++) {
            const item = this.tableData[i]
            if (this.$isEmpty(item.exceptionDesc)) {
              this.$message.warning(`请填写第${i + 1}行异常描述！`)
              return Promise.reject('')
            }
            if (this.$isEmpty(item.belongDuty)) {
              this.$message.warning(`请填写第${i + 1}行责任归属！`)
              return Promise.reject('')
            }
            if (this.typeCode === 'EXCEPT016' && this.$isEmpty(item.picTaskCode)) {
              this.$message.warning(`请选择第${i + 1}行图纸！`)
              return Promise.reject('')
            }
            if (!['EXCEPT017'].includes(this.typeCode) && !this.$gtZero(item.cutRegionArea)) {
              this.$message.warning(`请填写第${i + 1}行减少装修区域面积！`)
              return Promise.reject('')
            }
          }
        } else {
          this.tableData = []
        }
        const shopAttachmentDTOS = this.$getFiles(this.files, this.detail.id)
        if (['EXCEPT017'].includes(this.typeCode) && shopAttachmentDTOS.filter(e => e.dr !== 1 && e.dr !== '1').length === 0) {
          this.$message.warning('至少上传一个装修过程异常附件！')
          return
        }
        const data = {}
        data.constCode = this.detail.constCode
        data.bizCode = this.detail.decorationTaskCode
        data.modelId = this.detail.id
        const fd = this.formData
        data.exceptionHandleId = fd.exceptionHandleId
        data.handler = fd.handler
        data.exceptionDesc = fd.exceptionDesc
        data.shopAttachmentDTOS = shopAttachmentDTOS
        data.shopExceptionDetailDTOS = []
        this.tableData.forEach(e => {
          e = { ...e }
          if (this.typeCode === 'EXCEPT017' && fd.isSampleChange !== '') {
            e.isSampleChange = fd.isSampleChange
          }
          data.shopExceptionDetailDTOS.push(e)
        })
        if (data.shopExceptionDetailDTOS.length === 0) {
          const t = {
            expectRestoreTime: fd.expectRestoreTime,
            afterAdjustTime: fd.afterAdjustTime,
            delayDay: fd.delayDay,
            expectEndTime: fd.expectEndTime,
            // isSampleChange: fd.isSampleChange,
            exceptionDesc: fd.exceptionDesc,
            remark: '',
            stopTime: this.typeCode === 'EXCEPT013' ? this.$parseTime(new Date()) : ''
          }
          // if(){
          //   expectDecorationTime // 延期进场 EXCEPT136
          // expectEndTime // 施工周期延期 EXCEPT019
          // }
          if (this.typeCode === 'EXCEPT017' && fd.isSampleChange !== '') {
            t.isSampleChange = fd.isSampleChange
          }
          if (this.typeCode === 'EXCEPT136') {
            t.beforeAdjustTime = this.detail.expectDecorationTime
          } else if (this.typeCode === 'EXCEPT019') {
            t.beforeAdjustTime = this.detail.expectEndTime
            t.afterAdjustTime = fd.expectEndTime
          }
          data.shopExceptionDetailDTOS.push(t)
        }

        return postShopException(data).then(res => {
          this.$message.success('操作成功！')
          this.$refs.dialog.visible = false
          this.$emit('on-success')
        })
      })
    },
    cancelHandle() {
      this.$refs.dialog.visible = false
    },
    closeHandle() {
      this.tableData = []
      this.files = []
      this.selections = []
      this.typeCode = ''
      this.handlerName = ''
    }
  }
}
</script>
